var crypto = require('crypto')
//加密数据---备用
const encodeCryptData = () => {

}
//解密数据
const decryptData = (encryptedData, iv, appId, sessionKey) => {
  console.log("调用解密方法，传入的数据为：",encryptedData,'iv: ',iv)
  sessionKey = Buffer.from(sessionKey, 'base64')
  encryptedData = Buffer.from(encryptedData, 'base64')
  iv = Buffer.from(iv, 'base64')
  let decoded = undefined
  try {
     // 解密
    let decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
    // 设置自动 padding 为 true，删除填充补位
    decipher.setAutoPadding(true)
    decoded = decipher.update(encryptedData, 'binary', 'utf8')
    decoded += decipher.final('utf8')
    decoded = JSON.parse(decoded)
  } catch (err) {
    throw new Error('Illegal Buffer')
  }
  if (decoded.watermark.appid !== appId) {
    throw new Error('Illegal Buffer')
  }
  return decoded
}

module.exports = {
  decryptData,
  encodeCryptData
}
